package com.study.common;

import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @param <T> data type
 * @author yu xiaobo
 */
@Data
@NoArgsConstructor
public class CommonResponse<T> {

    @ApiModelProperty("0： 成功， 其他： 失败")
    int code;

    @ApiModelProperty(value = "错误消息", hidden = true)
    String msg;

    @ApiModelProperty("错误堆栈，用于调试")
    String errorDetail;

    @ApiModelProperty("接口数据")
    T data;

    @ApiModelProperty("是否成功")
    @JsonIgnore
    public boolean isSuccess() {
        return this.code == 0;
    }

    public CommonResponse(T data) {
        this.data = data;
    }

    public CommonResponse(int code, String message) {
        this.code = code;
        this.msg = message;
    }

    public CommonResponse(int code, String msg, Throwable throwable) {
        this.code = code;
        this.msg = msg;
        this.errorDetail = throwable == null ? "" : throwable.toString();
    }

    public static <T> CommonResponse<T> ok() {
        return new CommonResponse<>();
    }


    /**
     * 兼容
     *
     * @return code str
     */
    public String getRet() {
        return code + "";
    }


    /**
     * 兼容 retmsg
     *
     * @return
     */
    public String getRetmsg() {
        return getMsg();
    }
}
